package vn.com.bookstore.daoImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import vn.com.bookstore.dao.SupportNewsDao;
import vn.com.bookstore.domain.model.SearchResult;
import vn.com.bookstore.domain.model.SupportNews;
import vn.com.bookstore.utils.DaoHelper;

@Repository
public class SupportNewsDaoImpl extends DaoHelper<SupportNews> implements SupportNewsDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<SupportNews> getAllSupportNews() {
		String sql = "SELECT * FROM support_news WHERE active = 1";
		SearchResult<SupportNews> result = query(sql, null, new SupportNewsRowMapper());
		if (result == null || result.getSearchResult() == null) {
			return new ArrayList<SupportNews>();
		}
		return result.getSearchResult();
	}
	
	@SuppressWarnings("rawtypes")
	class SupportNewsRowMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			SupportNews supportNews = new SupportNews();
			supportNews.setId(rs.getInt("id"));
			supportNews.setContent(rs.getString("content"));
			supportNews.setTitle(rs.getString("title"));
			supportNews.setActive(rs.getInt("active"));
			supportNews.setUrlImage(rs.getString("url_image"));
			return supportNews;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public SupportNews getSupportNewsById(int id) {
		String sql = "SELECT * FROM support_news WHERE active = 1 AND id = ? ";
		Object[] params = new Object[]{id};
		SearchResult<SupportNews> result = query(sql, params, new SupportNewsRowMapper());
		if (result == null || result.getSearchResult() == null) {
			return new SupportNews();
		}
		return result.getSearchResult().get(0);
	}

}
